<template>
    <div class="chat-wrapper">
        <el-card class="chat-container">
            <div class="chat-header">
                <h2>小企帐助手</h2>
            </div>

            <div class="chat-body">
                <div class="chat-messages" ref="messageContainer">
                    <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
                        <div class="avatar">
                            <el-avatar :size="40" :src="message.role === 'user' ? userAvatar : aiAvatar"></el-avatar>
                        </div>
                        <div class="message-content">
                            <div class="message-text" v-html="formatMessage(message.content)"></div>
                        </div>
                    </div>
                </div>

                <div class="chat-input">
                    <el-input v-model="inputMessage" type="textarea" :rows="3" placeholder="请输入消息内容（按Enter发送）"
                        @keyup.enter.native="handleEnter" resize="none" />
                    <div class="button-group">
                        <el-button type="primary" @click="sendMessage" :loading="loading"
                            icon="el-icon-s-promotion">发送</el-button>
                        <el-button @click="clearChat" icon="el-icon-delete">清除对话</el-button>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import { sendMessage, clearChat } from '@/api/ai/chat';

export default {
    name: 'AiChat',
    data() {
        return {
            messages: [],
            inputMessage: '',
            loading: false,
            userAvatar: require('@/assets/images/user-avatar.svg'),
            aiAvatar: require('@/assets/images/ai-avatar.svg'),
        };
    },
    methods: {
        async sendMessage() {
            if (!this.inputMessage.trim()) {
                this.$message.warning('请输入消息内容');
                return;
            }

            const userMessage = this.inputMessage;
            this.messages.push({
                role: 'user',
                content: userMessage,
            });

            this.inputMessage = '';
            this.loading = true;

            try {
                const response = await sendMessage(userMessage);
                if (response.code === 200 && response.data) {
                    this.messages.push({
                        role: 'assistant',
                        content: response.data,
                    });
                } else {
                    this.messages.push({
                        role: 'assistant',
                        content: response.msg || '服务异常，请稍后重试',
                    });
                }
            } catch (error) {
                this.$message.error('发送消息失败');
                this.messages.push({
                    role: 'assistant',
                    content: '网络异常，请稍后重试',
                });
            } finally {
                this.loading = false;
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
            }
        },
        handleEnter(event) {
            if (!event.shiftKey) {
                this.sendMessage();
            }
        },
        async clearChat() {
            try {
                const response = await clearChat();
                if (response.code === 200) {
                    this.messages = [];
                    this.$message.success('对话已清除');
                } else {
                    this.$message.error(response.msg || '清除对话失败');
                }
            } catch (error) {
                this.$message.error('清除对话失败');
            }
        },
        scrollToBottom() {
            const container = this.$refs.messageContainer;
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        },
        formatMessage(content) {
            if (!content) return '';
            return content
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
                .replace(/\n/g, '<br>');
        },
    },
};
</script>

<style lang="scss" scoped>
.chat-wrapper {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0f2f5;
    padding: 20px;
    box-sizing: border-box;
    overflow: hidden;

    .chat-container {
        width: 100%;
        max-width: 900px;
        height: 700px;
        display: flex;
        flex-direction: column;
        border-radius: 8px;
        background-color: white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

        .chat-header {
            padding: 16px 24px;
            background: linear-gradient(135deg, #409eff, #36d1dc);
            color: white;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            flex: 0 0 auto;

            h2 {
                margin: 0;
                font-size: 1.25rem;
                font-weight: 500;
            }
        }

        .chat-body {
            flex: 1 1 auto;
            display: flex;
            flex-direction: column;
            background-color: #f8fafc;
            min-height: 0;

            .chat-messages {
                flex: 1;
                overflow-y: auto;
                padding: 24px;
                min-height: 0;
                scroll-behavior: smooth;

                &::-webkit-scrollbar {
                    width: 8px;
                    background-color: transparent;
                }

                &::-webkit-scrollbar-thumb {
                    background-color: rgba(0, 0, 0, 0.15);
                    border-radius: 4px;
                    transition: background-color 0.3s;

                    &:hover {
                        background-color: rgba(0, 0, 0, 0.3);
                    }
                }

                .message {
                    display: flex;
                    margin-bottom: 20px;
                    animation: fadeIn 0.3s ease-out;

                    .avatar {
                        margin-right: 12px;
                        flex-shrink: 0;
                    }

                    .message-content {
                        flex: 1;
                        max-width: calc(100% - 52px);

                        .message-text {
                            padding: 12px 16px;
                            border-radius: 8px;
                            background-color: white;
                            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
                            word-break: break-word;
                        }
                    }

                    &.assistant .message-text {
                        background-color: #e3f2fd;
                    }
                }
            }

            .chat-input {
                flex: 0 0 auto;
                padding: 20px 24px;
                background-color: white;
                border-top: 1px solid #ebeef5;

                .button-group {
                    margin-top: 12px;
                    display: flex;
                    justify-content: flex-end;
                    gap: 12px;
                }
            }
        }
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
